#define _CRT_SECURE_NO_WARNINGS  1

#include"mylist.h"


SLTNode* CreatNode(SLTDataType x)
{
	SLTNode* newnode = new SLTNode;

	newnode->val = x;
	newnode->next = NULL;

	return newnode;
}

void SLTPrint(SLTNode* phead)
{
	SLTNode* cur = phead;
	while (cur)
	{
		printf("%d->", cur->val);
		cur = cur->next;
	}
	printf("NULL\n");
}

void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	SLTNode* cur = *pphead;
	SLTNode* newnode = CreatNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		while (cur->next)
		{
			cur = cur->next;
		}
		cur->next = newnode;
	}
}

void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	SLTNode* newnode = CreatNode(x);
	newnode->next = *pphead;
	*pphead = newnode;
}

void SLTPopBack(SLTNode** pphead)
{
	if ((*pphead)->next == NULL)
	{
		delete* pphead;
		*pphead = NULL;
	}
	else
	{
		SLTNode* cur = *pphead;
		while (cur->next->next)
		{
			cur = cur->next;
		}
		delete cur->next;
		cur->next = NULL;
	}
}


void SLTPopFront(SLTNode** pphead)
{
	SLTNode* cur = *pphead;
	*pphead = cur->next;
	delete cur;
	cur = NULL;
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	SLTNode* cur = phead;
	while (cur->next)
	{
		if (cur->val == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

//pos front
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	SLTNode* cur = *pphead;
	SLTNode* prev = NULL;
	SLTNode* newnode = CreatNode(x);

	if (pos == *pphead)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		while (cur->next)
		{
			if (cur == pos)
			{
				newnode->next = cur;
				prev->next = newnode;
				break;
			}
			prev = cur;
			cur = cur->next;
		}
	}
}

void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	if (pos == *pphead)
		SLTPopFront(pphead);
	else
	{
		SLTNode* cur = *pphead;
		while (cur->next->next)
		{
			if (cur->next == pos)
			{
				cur->next = pos->next;
				pos->next = NULL;
				delete pos;
			}
			cur = cur->next;
		}
	}
}